import React, { useEffect, FormEvent, MutableRefObject } from "react";
import $ from "jquery";

// 过期时间：48 小时
export const MAX_AGE = +new Date() + 48 * 1000 * 60 * 60;

interface ModalProps{
    submitNickname: () => void;
    handleInput: ((e: React.FormEvent<HTMLInputElement>) => void) & _.Cancelable;
    modalRef: MutableRefObject<HTMLDivElement | null>;
    iptRef: MutableRefObject<HTMLInputElement | null>;
}

function Modal(props: ModalProps) {

    const { submitNickname, handleInput, modalRef, iptRef } = props;
    
    useEffect(() => {
        $(modalRef.current as HTMLDivElement).modal('show').on("shown.bs.modal",() => {
            $(iptRef.current as HTMLInputElement).focus();
        });
    }, [modalRef, iptRef]);

    return (
        <>
            <button type="button" className="btn btn-primary modal-btn d-none" data-target="#exampleModal" data-toggle="modal">Large modal</button>
            <div ref={modalRef} className="modal fade" role="dialog" id="exampleModal" data-backdrop="static" aria-hidden="true">
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title">输入昵称：</h5>
                        </div>
                        <div className="modal-body">
                            <form onSubmit={(e) => {e.preventDefault(); submitNickname()}}>
                                <div className="form-group">
                                    <label htmlFor="recipient-name" className="col-form-label">昵称:</label>
                                    <input 
                                        ref={iptRef} 
                                        onInput={(e: FormEvent<HTMLInputElement>) => { e.persist(); handleInput(e) }}
                                        type="text"
                                        className="form-control"
                                        id="recipient-name"
                                        maxLength={12}
                                        minLength={1}
                                    />
                                </div>
                            </form>
                        </div>
                        <div className="modal-footer">
                            <button onClick={submitNickname} type="button" className="btn btn-primary">提交</button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

export default Modal;